package com.tianzehua.netty.websocketexample;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * websocket channel initializer{@link ChannelInitializer}
 * @author tianzehua
 * @date 2019/03/10
 */
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline channelPipeline = ch.pipeline();

        channelPipeline.addLast(new HttpServerCodec());
        /* 分块处理的处理器 */
        channelPipeline.addLast(new ChunkedWriteHandler());
        /* http 请求聚合处理器 */
        channelPipeline.addLast(new HttpObjectAggregator(8192));
        /* This handler does all the heavy lifting for you to run a websocket server.
        It takes care of websocket handshaking as well as processing of control frames (Close, Ping, Pong). */
        channelPipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        channelPipeline.addLast(new TestWebSocketFrameHandler());
    }
}
